import api from '../../api';
import { PAGINATION } from '../../../constants/common';
import { apiModeUtils } from '../../apiConfig';
import type { User, Role, Department, Team } from '../../../types/rbac';

/**
 * 用户列表查询参数（对应后端SysUserQuery）
 */
export interface UserListParams {
  current?: number;
  size?: number;
  account?: string;
  username?: string;
  realName?: string;
  email?: string;
  phone?: string;
  status?: number; // 1-启用，0-禁用，2-锁定
  gender?: number;
  roleId?: number;
  roleCode?: string;
  departmentId?: number;
  keyword?: string;
  minAge?: number;
  maxAge?: number;
  orderBy?: string;
  orderType?: 'asc' | 'desc';
}

/**
 * 创建用户请求参数（对应后端SysUserDto）
 */
export interface CreateUserRequest {
  account: string;
  username: string;
  email: string;
  password: string;
  realName?: string;
  phone?: string;
  status?: number; // 1-启用，0-禁用，2-锁定
  avatar?: string;
  gender?: number;
  age?: number;
  description?: string;
  // 支持简化引用格式
  roleIds?: string[];
  departmentIds?: string[];
  teamIds?: string[];
}

/**
 * 更新用户请求参数（对应后端SysUserDto）
 */
export interface UpdateUserRequest {
  id?: string;
  account?: string;
  username?: string;
  email?: string;
  realName?: string;
  phone?: string;
  status?: number;
  avatar?: string;
  gender?: number;
  age?: number;
  description?: string;
  // 支持简化引用格式
  roleIds?: string[];
  departmentIds?: string[];
  teamIds?: string[];
}

/**
 * 用户列表响应类型（对应后端分页响应）
 */
export interface UserListResponse {
  records: User[];
  total: number;
  size: number;
  current: number;
  pages: number;
  hasPrevious: boolean;
  hasNext: boolean;
}

/**
 * 重置密码请求参数
 */
export interface ResetPasswordRequest {
  userId: string;
  newPassword: string;
}

/**
 * 批量操作用户请求参数
 */
export interface BatchUserRequest {
  userIds: string[];
  action: 'activate' | 'deactivate' | 'delete';
}

/**
 * 用户分配数据响应类型
 */
export interface UserAssignmentData {
  roles: Role[];
  departments: Department[];
  teams: Team[];
}

/**
 * 用户统计信息
 */
export interface UserStats {
  totalUsers: number;
  activeUsers: number;
  inactiveUsers: number;
  newUsersThisMonth: number;
  usersByDepartment: Array<{
    departmentId: string;
    departmentName: string;
    count: number;
  }>;
  usersByRole: Array<{
    roleId: string;
    roleName: string;
    count: number;
  }>;
}

/**
 * 导入结果
 */
export interface ImportResult {
  success: number;
  failed: number;
  errors: string[];
}

/**
 * 用户管理API服务 - 使用优化的API包装器
 * 注意：通过网关调用v3-system服务，路径需要以/system开头
 * 网关配置：Path=/system/** + StripPrefix=1，会自动去掉/system前缀
 */

// 创建用户API包装器
const api_user = apiModeUtils.createApi('userApi', api, false);

export const userApi = {
  /**
   * 获取用户列表（分页）
   */
  getUsers: async (params?: UserListParams): Promise<UserListResponse> => {
    const requestData = {
      current: params?.current || 1,
      size: params?.size || PAGINATION.DEFAULT_PAGE_SIZE,
      ...params,
    };
    return api_user.post('getUsers', '/system/api/v3/sys/users/page', requestData);
  },

  /**
   * 获取所有用户（不分页）
   */
  getAllUsers: (): Promise<User[]> => {
    return api_user.get('getAllUsers', '/system/api/v3/sys/users/all');
  },

  /**
   * 获取用户详情
   */
  getUser: (id: string): Promise<User> => {
    return api_user.get('getUser', `/system/api/v3/sys/users/get/${id}`);
  },

  /**
   * 创建用户
   */
  createUser: (data: CreateUserRequest): Promise<User> => {
    return api_user.post('createUser', '/system/api/v3/sys/users/add', data);
  },

  /**
   * 更新用户
   */
  updateUser: (data: UpdateUserRequest): Promise<User> => {
    return api_user.put('updateUser', '/system/api/v3/sys/users/update', data);
  },

  /**
   * 删除用户
   */
  deleteUser: (id: string): Promise<void> => {
    return api_user.delete('deleteUser', `/system/api/v3/sys/users/delete/${id}`);
  },

  /**
   * 批量删除用户
   */
  batchDeleteUsers: (ids: string[]): Promise<void> => {
    return api_user.delete('batchDeleteUsers', '/system/api/v3/sys/users/batch', { data: { ids } });
  },

  /**
   * 根据用户名获取用户
   */
  getUserByUsername: (username: string): Promise<User> => {
    return api_user.get('getUserByUsername', `/system/api/v3/sys/users/username/${username}`);
  },

  /**
   * 获取用户权限
   */
  getUserPermissions: (userId: string): Promise<any[]> => {
    return api_user.get('getUserPermissions', `/system/api/v3/sys/users/${userId}/permissions`);
  },

  /**
   * 重置用户密码
   */
  resetPassword: (data: ResetPasswordRequest): Promise<void> => {
    return api_user.put('resetPassword', `/system/api/v3/sys/users/${data.userId}/password`, { 
      password: data.newPassword 
    });
  },

  /**
   * 启用/禁用用户
   */
  toggleUserStatus: (id: string, status: number): Promise<void> => {
    return api_user.put('toggleUserStatus', `/system/api/v3/sys/users/${id}/status`, { status });
  },

  /**
   * 批量操作用户
   */
  batchUpdateUsers: (data: BatchUserRequest): Promise<void> => {
    return api_user.put('batchUpdateUsers', '/system/api/v3/sys/users/batch', data);
  },

  /**
   * 检查用户名是否存在
   */
  checkUsername: (username: string, excludeId?: string): Promise<{ exists: boolean }> => {
    return api_user.get('checkUsername', '/system/api/v3/sys/users/check-username', { 
      params: { username, excludeId } 
    });
  },

  /**
   * 检查邮箱是否存在
   */
  checkEmail: (email: string, excludeId?: string): Promise<{ exists: boolean }> => {
    return api_user.get('checkEmail', '/system/api/v3/sys/users/check-email', { 
      params: { email, excludeId } 
    });
  },

  /**
   * 获取用户统计信息
   */
  getUserStats: (): Promise<UserStats> => {
    return api_user.get('getUserStats', '/system/api/v3/sys/users/stats');
  },

  /**
   * 导出用户数据
   */
  exportUsers: (params?: UserListParams): Promise<Blob> => {
    return api_user.get('exportUsers', '/system/api/v3/sys/users/export', { 
      params,
      responseType: 'blob'
    });
  },

  /**
   * 导入用户数据
   */
  importUsers: (file: File): Promise<ImportResult> => {
    const formData = new FormData();
    formData.append('file', file);
    return api_user.post('importUsers', '/system/api/v3/sys/users/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },

  /**
   * 根据部门ID查询用户
   */
  getUsersByDepartmentId: (departmentId: string): Promise<User[]> => {
    return api_user.get('getUsersByDepartmentId', `/system/api/v3/sys/users/department/${departmentId}`);
  },

  /**
   * 获取用户分配数据（角色、部门、团队）
   */
  getUserAssignmentData: (): Promise<UserAssignmentData> => {
    return api_user.get('getUserAssignmentData', '/system/api/v3/sys/users/assignment-data');
  },
};